<template>
  <div class="chart-container">
    <div ref="chart" class="chart-content"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'LineChart',
  props: {
    chartData: {
      type: Object,
      required: true,
    },
    chartOptions: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      chart: null,
      defaultOption: {
        backgroundColor: 'transparent',
        title: {
          text: '折线图',
          textStyle: {
            color: '#fff',
          },
        },
        tooltip: {
          trigger: 'axis',
        },
        xAxis: {
          type: 'category',
          data: [],
          axisLine: {
            lineStyle: {
              color: '#fff',
            },
          },
          axisLabel: {
            color: '#fff',
          },
        },
        yAxis: {
          type: 'value',
          axisLine: {
            lineStyle: {
              color: '#fff',
            },
          },
          axisLabel: {
            color: '#fff',
          },
        },
        series: [
          {
            type: 'line',
            data: [],
          },
        ],
      },
    }
  },
  mounted() {
    this.initChart()
  },
  methods: {
    initChart() {
      if (this.chart) {
        this.chart.dispose()
      }
      this.chart = echarts.init(this.$refs.chart)

      // 合并默认配置和传入的数据
      const option = this.mergeOptions()
      this.chart.setOption(option)

      // 监听容器大小变化
      const resizeObserver = new ResizeObserver(() => {
        this.chart.resize()
      })
      resizeObserver.observe(this.$refs.chart)
    },

    mergeOptions() {
      // 深度合并配置
      const option = JSON.parse(JSON.stringify(this.defaultOption))

      if (this.chartData.xAxis?.data) {
        option.xAxis.data = this.chartData.xAxis.data
      }

      if (this.chartData.series) {
        option.series = this.chartData.series
      }

      if (this.chartData.title) {
        option.title = this.chartData.title
      }

      return { ...option, ...this.chartOptions }
    },

    refreshChart() {
      if (this.chart) {
        const option = this.mergeOptions()
        this.chart.setOption(option, true) // true 表示不合并之前的配置
      }
    },
  },
  watch: {
    chartData: {
      handler() {
        this.refreshChart()
      },
      deep: true,
    },
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
    }
  },
}
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  padding: 10px;
  background: transparent;
  position: relative;
}

.chart-content {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}
</style> 